﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Folding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace 雷赛板卡上位机.Models
{
    public class EditorFoldingService
    {
        private FoldingManager _foldingManager;
        private TextEditor _editor;

        public void Attach(TextEditor editor)
        {
            _editor = editor;
            _foldingManager = FoldingManager.Install(_editor.TextArea);
            _editor.TextChanged += UpdateFoldings;
            UpdateFoldings(null, null); // 初始更新
        }

        private void UpdateFoldings(object sender, EventArgs e)
        {

            var newFoldings = new List<NewFolding>();
            var text = _editor.Document.Text;

            // 匹配 function-end 块（支持嵌套）
            var stack = new Stack<int>();
            var matches = Regex.Matches(text, @"\b(function|if|for|while)\b|\bend\b");

            foreach (Match match in matches)
            {
                if (match.Value == "function" || match.Value == "if" || match.Value == "for" || match.Value == "while")
                {
                    stack.Push(match.Index);
                }
                else if (match.Value == "end" && stack.Count > 0)
                {
                    int start = stack.Pop();
                    newFoldings.Add(new NewFolding(start, match.Index + match.Length)
                    {
                        Name = "代码块",
                        DefaultClosed = false
                    });
                }
            }
            try
            {
                _foldingManager.UpdateFoldings(newFoldings, -1);
            }
            catch (Exception ex)
            {

            }
        }
    }
}
